<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <title>Mapa Beni</title>
        <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3&key=AIzaSyDzpJACBJTRWirTRyuAnUkw6LwPhN2pxDk&sensor=false&language=ca"></script>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript"> 
    // Get the URL variables
	var arrURL=window.location.search.substr(1).split("&");
	for (i=0;i<arrURL.length;i++) {
		arrURL[i]=arrURL[i].split("=");
	}
	var qStr=[];
	for (i=0;i<arrURL.length;i++) {
		qStr[arrURL[i][0]]=arrURL[i][1];
	}
	if (qStr['bzoom']!=null) {
		var	bzoom = parseInt(qStr['bzoom']);
	} else {
		var	bzoom = 16;
	}

	// Initial variables
	var mapwidth = 480; 
	var map;
	sidebarmarkers = [];
	stylesdb = {};
	styleurldb = {};
	sidebarhtml = '<form name="form_c" id="form_c">';
	j = 0;
	s = 0;
   
	var maptiler = new google.maps.ImageMapType({ 
		getTileUrl: function(a, b) { 
				var tile = "maptiles/zoom"+b+"/"+a.x+"_"+a.y+"_"+b+".png";
				switch (b) {
					case 5:
					if ((a.x==15||a.x==16) && a.y==12) {
						return tile;
					}
					break;
					case 6:
					if ((a.x==31||a.x==32) && a.y==24) {
						return tile;
					}
					break;
					case 7:
					if ((a.x==63||a.x==64) && a.y==48) {
						return tile;
					}
					break;
					case 8:
					if ((a.x==127||a.x==128) && a.y==97) {
						return tile;
					}
					break;
					case 9:
					if ((a.x==255||a.x==256) && a.y==194) {
						return tile;
					}
					break;
					case 10:
					if (a.x==511 && a.y==388) {
						return tile;
					}
					break;
					case 11:
					if (a.x==1022 && a.y==777) {
						return tile;
					}
					break;
					case 12:
					if (a.x==2044 && a.y==1554) {
						return tile;
					}
					break;
					case 13:
					if (a.x==4089 && a.y==3109) {
						return tile;
					}
					break;
					case 14:
					if (a.x==8179 && a.y==6218) {
						return tile;
					}
					break;
					case 15:
					if ((a.x==16358||a.x==16359) && a.y==12437) {
						return tile;
					}
					break;
					case 16:
					if (a.x>=32717 && a.x<=32719 && a.y>=24874 && a.y<=24875) {
						return tile;
					}
					break;
					case 17:
					if (((a.x>=65436 && a.x<=65438 && a.y>=49748 && a.y<=49751) || (a.x==65435 && a.y==49750)|| (a.x==65439 && a.y==49750))) {
						return tile;
					}
				}
			}, 
			tileSize: new google.maps.Size(256, 256), 
		}); 


		function toggleMarker(m,n){
			//map.infoWindow.close();	
			switch (n) {
			case 1: // for list menu markers
				for (var i = 0; i < sidebarmarkers.length; i++) {
					sidebarmarkers[i].setMap(null);
				}
				sidebarmarkers[m].setMap(map);
				google.maps.event.trigger(sidebarmarkers[m], "click");	
				break;
			case 2: // for list menu polylines
				for (var i = 0; i < sidebarmarkers.length; i++) {
					sidebarmarkers[i].setMap(null);
				}
				//sidebarmarkers.forEach(setMap(null));
				sidebarmarkers[m].setMap(map);
				break;
			case 3: // for links
				if (document.getElementById("check"+m).checked==false) {
					document.getElementById("check"+m).checked=true;
					sidebarmarkers[m].setMap(map);
					google.maps.event.trigger(sidebarmarkers[m], "click");
				} else {
					document.getElementById("check"+m).checked=false;
					sidebarmarkers[i].setMap(null);
				}
				break;
			case 4: // for clearing all selects and overlays on zoomout
				for (var i = 0; i < sidebarmarkers.length; i++) {
					sidebarmarkers[i].setMap(null);
				}
				if (document.form_c) {
					document.form_c.reset();
				}
			}	
		}	
      
	function createMarker(lat, lon, locname, desc, iconhref) {
		var marker = new google.maps.Marker({
			icon: new google.maps.MarkerImage(iconhref),
			position: new google.maps.LatLng(parseFloat(lat),parseFloat(lon))
		});
		var infoWindow = new google.maps.InfoWindow();
		google.maps.event.addListener(marker, "click", function() {
			infoWindow.setContent(desc);
   			infoWindow.open(map,this);
		});
		sidebarmarkers.push(marker);
		sidebarhtml += '<option value="'+sidebarmarkers.indexOf(marker)+'">' + locname + '</option>\n';
	}
	
	function createLine(points, locname) {
		var pline = new google.maps.Polyline({
		path: points,
		strokeColor:'#FF0000',
		strokeWeight: 10, 
		strokeOpacity: 0.4
		});
		sidebarmarkers.push(pline);
		sidebarhtml += '<option value="'+sidebarmarkers.indexOf(pline)+'">' + locname + '</option>\n';		
	}
	
	function showhideSidebar() {
		if (map.getZoom()>14) {
			document.getElementById('mapbox').style.width = mapwidth+'px';
			document.getElementById('sidebar').style.display='block';
		} else {
			toggleMarker(-1,4);
			document.getElementById('mapbox').style.width = (mapwidth+150)+'px';
			document.getElementById('sidebar').style.display='none';
		}
	}
	
function initialize() {

	map = new google.maps.Map(document.getElementById("mapbox"), {
	zoom: 16,
	maxZoom: 17,
	center: new google.maps.LatLng(39.72789258893543, -0.2694869041442871),
	mapTypeId: google.maps.MapTypeId.ROADMAP
	});
	
	// for dynamical hide/show of marker navbar
  google.maps.event.addListener(map, 'zoom_changed', function(){showhideSidebar();});
	// initial zoom detect for display
	showhideSidebar();
	
	map.overlayMapTypes.insertAt(0, maptiler);
	
	$.ajax({
	async: false,
	type: 'GET',
	url: "benifairo.kml",
	success: function(data) {
	//downloadUrl("benifairo.kml", function(data) {
	
  	var pfolders = data.documentElement.getElementsByTagName("Folder");  		
  	for (var j = 0; j < pfolders.length; j++) {
  		// for xml 'folder' containing placemarks -> dropdown list
		if (pfolders[j].getElementsByTagName("name")[0].firstChild.nodeValue == "Serveis públics") {
			var placemarks = pfolders[j].getElementsByTagName("Placemark");
			for (var i = 0; i < placemarks.length; i++) {
				var locname = placemarks[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
				coordinates = placemarks[i].getElementsByTagName("coordinates")[0].childNodes[0].nodeValue.split(",");					
				stylesdb[placemarks[i].getElementsByTagName("styleUrl")[0].childNodes[0].nodeValue.substring(1)] = {
					place : locname,
					lat :	parseFloat(coordinates[1]),
					lon : parseFloat(coordinates[0]),
					desc : placemarks[i].getElementsByTagName("description")[0] ? placemarks[i].getElementsByTagName("description")[0].childNodes[0].nodeValue : ''
				}
			}
		}
		// for xml 'folder' containing polylines -> dropdown list
		if (pfolders[j].getElementsByTagName("name")[0].firstChild.nodeValue == "Carrers") {
			var placemarks = pfolders[j].getElementsByTagName("Placemark");
			sidebarhtml += 'Selecciona un carrer:<br /><select name="menu1" size="8" onchange="toggleMarker(this.options[this.selectedIndex].value,2)"><option value="-1" selected="selected"></option>';
  			for (var i = 0; i < placemarks.length; i++) {
  				var locname = placemarks[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
  				var coordinates = placemarks[i].getElementsByTagName("coordinates")[0].childNodes[0].nodeValue;
  				coordinates = coordinates.split(" ");
				for (var j=0; j<coordinates.length; j++) {
					coordinates[j] = coordinates[j].split(",");
				}
				var points = new Array();					
				for(var j=0; j<(coordinates.length-1); j++) {
					points.push(new google.maps.LatLng(coordinates[j][1],coordinates[j][0]));
				}
				createLine(points,locname);
			}
			sidebarhtml += '</select><br /><br />';
		}
	}
	
  	// <Style id="identifier"><href> ::: contains the URL for each icon
	var styleidarr = data.documentElement.getElementsByTagName("Style");
  	for (var i = 0; i < styleidarr.length; i++) {
  		styleurldb[styleidarr[i].getAttribute('id')] = {iconhref : styleidarr[i].getElementsByTagName("href")[0] ? styleidarr[i].getElementsByTagName("href")[0].childNodes[0].nodeValue : ''};
  	}
  		
	// <StyleMap id="identifier"><styleUrl> ::: contains the style id of each marker
  	var stylemapidarr = data.documentElement.getElementsByTagName("StyleMap");
  	sidebarhtml += 'Selecciona un servei:<br /><select name="menu2" size="8" onchange="toggleMarker(this.options[this.selectedIndex].value,1)"><option value="-1" selected="selected"></option>';
  	for (var i = 0; i < stylemapidarr.length; i++) {
  		var stylemapid = stylemapidarr[i].getAttribute('id');
  		if (stylesdb[stylemapid]!=null) {
  			stylesdb[stylemapid].styleurl = stylemapidarr[i].getElementsByTagName("styleUrl")[0] ? stylemapidarr[i].getElementsByTagName("styleUrl")[0].childNodes[0].nodeValue.substring(1) : '';
  			stylesdb[stylemapid].iconhref = styleurldb[stylesdb[stylemapid].styleurl].iconhref;
  		}
  	}
	for (i in stylesdb) {
		createMarker(stylesdb[i].lat, stylesdb[i].lon, stylesdb[i].place, stylesdb[i].desc, stylesdb[i].iconhref);
	}
  	sidebarhtml += '</select><br /><br />';
	document.getElementById("sidebar").innerHTML = sidebarhtml+"</form>";
	}
	}); 	 
}
        </script>
<style type="text/css">
	<!--
body {
	font-family: Arial, Helvetica, sans-serif;
	font-size: small;
}
a {
	text-decoration: none;
}
a:link {
	color: #009900;
}
a:visited {
	color: #00CC99;
}
a:hover {
	color: #00CC66;
}
a:active {
	color: #009999;
}
-->
</style>
    </head>
    <body onload="initialize()">
    <script type="text/javascript">
  	document.write('<div id="mapbox" style="width: '+mapwidth+'px; height: 500px; float: left"></div>');
  	</script>
  	<div id="sidebar" style="width: 150px; height: 500px; padding: 15px; float: left"></div>
  <div style="display: block; clear: both"><a href='javascript:void(0);' onclick='map.setCenter(new google.maps.LatLng(39.72789258893543, -0.2694869041442871))'>Centrar mapa</a></div>
    </body>
</html>